import pandas as pd
from py2neo import Graph, Node

df = pd.read_csv("books.csv")

books = set(df["name"])
authors = set(df["author"])
publishers = set(df["publisher"]) 
categories = set(df["category"])
keywords = set()
for each in df["keywords"]:
    keywords.update(each.split(";"))

rels_written_by = []
rels_published_by = []
rels_has_category = []
rels_has_keyword = []

for idx, row in df.iterrows():
    rels_written_by.append([row["name"], row["author"]])
    rels_published_by.append([row["name"], row["publisher"]])
    rels_has_category.append([row["name"], row["category"]])
    for kw in row["keywords"].split(";"):
        rels_has_keyword.append([row["name"], kw])

graph = Graph("bolt://localhost:7687", auth=("neo4j", "12345678"), name="neo4j")
cypher = "MATCH(n) DETACH DELETE n"
graph.run(cypher)

for name in books:
    row = df[df["name"] == name].iloc[0]
    node = Node(
        "Book",
        name=str(name),
        publish_year=int(row["publish_year"]),
        summary=str(row["summary"]),
    )
    graph.create(node)
    print(f"创建图书:{name}")

for author in authors:
    node = Node("Author", name=str(author))
    graph.create(node)
    print(f"创建作者:{author}")

for category in categories:
    node = Node("Category", name=str(category))
    graph.create(node)
    print(f"创建分类:{category}")

for publisher in publishers:
    node = Node("Publisher", name=str(publisher))
    graph.create(node)
    print(f"创建出版社:{publisher}")

for keyword in keywords:
    node = Node("Keyword", name=str(keyword))
    graph.create(node)
    print(f"创建出版社:{keyword}")

def create_relationship(start_label, end_label, edges, rel_type, rel_name):
    for edge in edges:
        p = str(edge[0])
        q = str(edge[1])
        query = (
            f"MATCH (p:{start_label}),(q:{end_label}) WHERE p.name='{p}' AND q.name='{q}'"
            f"CREATE (p)-[rel:{rel_type} {{name:'{rel_name}'}}]->(q)"
        )
        print(query)
        try:
            graph.run(query)
        except Exception as e:
            print(f"创建关系时发生错误:{e}")

create_relationship("Book", "Author", rels_written_by, "WRITTEN_BY", "作者")
create_relationship("Book", "Publisher", rels_published_by, "PUBLISHED_BY", "出版社")
create_relationship("Book", "Category", rels_has_category, "HAS_CATEGORY", "类别")
create_relationship("Book", "Keyword", rels_has_keyword, "HAS_KEYWORD", "关键词")
